package com.study.practice.db;

import java.sql.*;

public class dataMove {
    private Connection getMysqlConn(){
        try {
            // 注册数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection("jdbc:mysql://192.168.195.129:3306/practice?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT",
                    "root", "123456");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public  void  close(Connection conn, Statement stmt, ResultSet rs){

        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    public void deal() throws SQLException {
        //比较懒，拼接insert into 语句
        String sql = "insert into t_user(name,age,sex,addr) value(?,?,?,?)";
        //MySQL数据库
        Connection mysqlconn = getMysqlConn();
        PreparedStatement pstmt = mysqlconn.prepareStatement(sql);

        //取出结果集并向MySQL数据库插入数据 ( 使用批处理 )
        //完成条数
        int count =0;
        long start = System.currentTimeMillis();
        for(int i = 0; i < 10; i++) {
            pstmt.setString(1, "name" + i);
            pstmt.setInt(2, 20 + i);
            pstmt.setInt(3, 1);
            pstmt.setString(4, "老家");
            pstmt.addBatch();
            count++;
        }

        // 防止有数据未提交
        pstmt.executeBatch();
        System.out.println("完成 "+count+" 条数据,耗时:"+(System.currentTimeMillis()-start)/1000.0+"s");

        //关闭资源
        close(mysqlconn,pstmt,null);
    }

    public static void main(String[] args) {
        dataMove dataMove = new dataMove();

        try {
            dataMove.deal();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
